<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\Site;

/**
 * 获取前台广告模块数据
 *
 * @package Service\Site
 *         
 */
class Ads extends \Think\Model
{

    protected $name = 'ads';

    const ADS_STATUS_NORMAL=1;
    
    const ADS_STATUS_FORBIT=0;
    
    static $instace;

    public static function getInstance ()
    {
        self::$instace or self::$instace = new self();
        return self::$instace;
    }

    /*
     * 获取广告位下广告列表
     * @param mixed $position
     */
    public function get($position){
        if(!$position){
            throw new \Service\Util\KCException();
        }
        
        $where=array(
            'status'=>self::ADS_STATUS_NORMAL,
        );
        $where['category']=is_array($position)?array('in',$position):$position;
        
        $order='level desc';
        $list= $this->where($where)->order($order)->select();
        $response=array();
        //图片处理 且按广告位分组
        foreach($list as $k=>$v){
            $link=$v['link']?$v['link']:"javascript:void(0);";
            $target=$v['target']?'target=_blank':'';
            $v['link_label']="<a href='{$link}' {$target}>{$v['title']}</a>";
            $response[$v['category']][$k]=$v;
        }
        return $response;
    }
    
    /**
     * 获取广告分类(广告位）
     */
    public function getCategory(){
        $categoyiesCfg=C('BANNER_CATEGORY');
        $categoyiesArr=explode("\r\n",$categoyiesCfg);
        $category=array();
        foreach($categoyiesArr as $item){
            $itemInfo=explode(':',$item);
            $category[$itemInfo[0]]=$itemInfo[1];
        }
        return $category;
    }
    
    /*
     * 获取广告位分类下广告数量
     */
    function getAdsNumByCate(){
        $category=o('site')->getAdsCategory();
        $where=array(
            'category'=>array('in',array_keys($category))
        );
        $result=$this->field('count(id) as num,category')->group('category')->where($where)->index('category')->select();
        $result=$result?:array();
        $nums=array();
        foreach($category as $cate=>$cate_name){
            $nums[$cate]=isset($result[$cate])?$result[$cate]['num']:0;
        }
        $nums['_']=array_sum($nums);
        return $nums;
    }
}